<template>
    <el-container>
        <el-aside width="200px" style="text-align: center;">
            <div style="margin-top: 20px;">基本信息</div>
            <div style="margin-top: 230px;">商品相册</div>
            <div style="margin-top: 180px;">商品描述</div>
            <div style="margin-top: 220px;">其他信息</div>
        </el-aside>
        <el-main>
            <!-- 基本信息 -->
            <el-form :model="addlist" class="demo-form-inline">
                <el-form-item label="商品名称:">
                    <el-input v-model="name" placeholder="" clearable style="width: 300px" />
                </el-form-item>
                <el-form-item label="商品数量:">
                    <el-input v-model="amount" placeholder="请输入数字" clearable style="width: 300px" />
                </el-form-item>
                <el-form-item label="商品货号:">
                    <el-input v-model="artNo" placeholder="" clearable style="width: 300px" />
                    <p style="color: rgb(159, 156, 156);">如果你不输入商品货号，系统将自动生成一个唯一的货号。</p>
                </el-form-item>

                <el-form-item label="商品分类:">
                    <el-cascader v-model="value9" :options="options" :props="props" @change="handleChange"
                        style="width: 300px" />
                </el-form-item>
                <el-form-item label="商品售价:">
                    <el-input v-model="price" placeholder="" clearable style="width: 300px" />
                </el-form-item>
            </el-form>


            <!-- 上传图片 -->
            <el-upload :before-upload="beforeUpload" ref="upload" action="http://124.222.34.94:8080/admin/upload/image"
                list-type="picture-card" :auto-upload="false" :limit="1" :on-exceed="handleExceed"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleUploadSuccess"
                :on-error="handleUploadError">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-button type="primary" @click="submitUpload" style="margin-top: 10px;">
                点击上传
            </el-button>

            <!-- 富文本 -->
            <div style="border: 1px solid #ccc ;margin-top: 15px;">
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                    :mode="mode" />
                <Editor style="height: 150px; overflow-y: hidden;" v-model="description" :defaultConfig="editorConfig"
                    :mode="mode" @onCreated="handleCreated" />
            </div>

            <!-- 商家按钮 -->
            <el-form-item label="是否上架："><el-switch v-model="value" @click="btn" /></el-form-item>

            <!-- 操作按钮 -->
            <el-button @click="" type="primary">返回</el-button>
            <el-button @click="save" type="primary">保存</el-button>

        </el-main>
    </el-container>
</template>


<script setup lang="ts">
import { reactive } from 'vue';
import '@wangeditor/editor/dist/css/style.css';
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import axios from '../WuJiUtils/http';
import { genFileId, type UploadInstance, type UploadProps, type UploadRawFile } from 'element-plus';
let className = ref('')//二级分类名字
let lable = ref(1) //2为上架，1为下架
let name = ref('') //商品名称
let artNo = ref('')  //商品货号
let picture = ref('')//商品图片地址
let price = ref()//商品价格
let amount = ref()//商品数量
// interface _addlist { name: string, huohao: number, fenlei: string, money: number }
const addlist: any = reactive({})

// 富文本
const editorRef = shallowRef()

// 内容 HTML
const description = ref('')//富文本输入的内容为商品描述

// 模拟 ajax 异步获取内容
// onMounted(() => {
//     setTimeout(() => {
//         valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
//     }, 1500)
// })

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

const value = ref(true) //是否上架
const btn = () => {
    console.log(value);
    if (value.value) {
        lable.value = 2
    } else {
        lable.value = 1
    }
    console.log(lable);


}

const options: any = ref([])
const Hhuixian = () => {
    axios({
        url: '/ClassifycationController/findClassify',
        method: "get",
    }).then((res) => {
        // console.log(res.data.data);
        if (res.data.code == 0) {
            let fruits: any = [];
            // fruits.push(...res.data.data)
            fruits = res.data.data
            // console.log(fruits);
            options.value.length = 0
            fruits.forEach((item: any) => {
                //fruits每一项
                // console.log('fruits每一项');
                // console.log(item);
                // console.log('fruits每一项');
                //fruits每一项
                let childs: any = []
                // console.log(item.classNames);
                item.classNames ?
                    item.classNames.forEach((i: any) => {
                        childs.push({ value: i.className, label: i.className })
                    }) : childs = []
                // item.classNames.forEach((i: any) => {
                //     childs.push({ value: i.className, label: i.className })
                // })
                options.value.push({ value: item.className, label: item.className, children: childs })
            })
            //目标数组
            // console.log('目标数组');
            // console.log(options.value);
            // console.log('目标数组');
            //目标数组


        }
    })
}

onMounted(() => {
    Hhuixian()
})




const value9 = ref([])

const props = {
    expandTrigger: 'hover' as const,
}

const handleChange = (value) => {
    console.log(999, value)
    className.value = value[1]
}




// 图片上传
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
// 移除当前图片
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
};

// 查看当前图片放大效果
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
};

//文件上传之前的钩子函数
const beforeUpload = (file) => {
    // 自定义验证逻辑
    // 如果验证失败，返回 false 阻止上传
    // 如果验证通过，返回 true 允许上传
    //大多数浏览器将 JPG 文件的 MIME 类型设置为 "image/jpeg"
    if (file.type !== "image/png" && file.type !== "image/jpeg") {
        ElMessage({
            showClose: true,
            message: "请选择jpg或者png的图片文件",
            type: "warning",
        });
        return false;
    }
    if (file.size / 1024 / 1024 > 10) {
        ElMessage({
            showClose: true,
            message: "图片大小不能超过10MB",
            type: "warning",
        });
        return false;
    }
    // 验证通过，允许文件上传
    return true;
};

// 更新文件列表，只保留最新选择的文件
const upload = ref<UploadInstance>();
const handleExceed: UploadProps["onExceed"] = (files) => {
    // fileList = fileList.slice(-1);
    // console.log(files[0]);
    // console.log(fileList[0]);
    upload.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    upload.value!.handleStart(file);
};

//请求头携带token
// let getUploadHeaders = reactive({
//     // token: sessionStorage.getItem("token"),
//     token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODkwNDQzMTEwIiwiaW1hZ2VVcmwiOiJodHRwczovL3hxcS0xMzE5MjE5NTU1LmNvcy5hcC1jaGVuZ2R1Lm15cWNsb3VkLmNvbS9ob3NwaXRhbCUyRjMyNDAxNjg5Mzk5NTc4Njk2LnBuZyIsIm5hbWUiOiJhZG1pbiIsImV4cGlyZV90aW1lIjoxNjkwOTA1ODcyMjIzLCJwZXJtcyI6IltcImFkbWluXCJdIiwiaWQiOiIxIiwidXNlcm5hbWUiOiJhZG1pbiJ9.kkevIjR2JIBKMcXdlHVdTH5dEYz0Kc1EW5oGd2UZmTg'
// });

// 点击上传
const submitUpload = () => {
    // console.log(upload.value);
    upload.value!.submit();
};

//移除图片
// let remove_img = () => {
//     form.imgUrl = "";
// };

// 上传成功响应事件(文件上传成功后的回调函数)
let handleUploadSuccess = (res) => {
    console.log(res.data);
    // form.imgUrl = res.data;
    ElMessage({
        showClose: true,
        message: "文件上传成功",
        type: "success",
    });
    picture.value = res.data
    console.log(picture);

};

// 上传失败响应事件(文件上传失败后的回调函数)
let handleUploadError = (err) => {
    // console.log("错误信息:", err);
    ElMessage({
        showClose: true,
        message: "文件上传失败",
        type: "info",
    });
};



const save = () => {
    let editor: any = ref('')
    editor = editorRef.value
    description.value = editor.getText()
    // console.log(description.value);
    // console.log(name.value);
    // console.log(lable.value);
    // console.log(artNo.value);
    // console.log(amount.value);
    // console.log(price.value);
    // console.log(picture.value);

    axios({
        url: '/CommodityController/insert',
        method: 'post',
        data: { description: description.value, className: className.value, lable: lable.value, name: name.value, artNo: artNo.value, picture: picture.value, price: price.value, amount: Number(amount.value) }
    }).then((res) => {
        if (res.data.code == 0) {
            ElMessage({
                showClose: true,
                message: "保存成功",
                type: "success",
            })
        }
    })

}




</script>

<style lang="less"></style>